<?php
namespace App\Http\Lib;

use App\Models\User as UserModel;
use App\Entity\UserEntity;
use Illuminate\Http\Request;

class UserLib 
{
    static public function username() {
        return 'name';
    }
    
    /* 获取当前登录的用户信息
     return false | UserEntity
     */
    static public function getUserFromToken(Request $request) {
        $ue = app()->make(UserEntity::class);
    
        if(empty($ue->_id)) {
            $token = Parser::parseToken($request);
            
            if($token) {
                $um = UserModel::where('api_token', $token)->first();
                if(!$um) {
                    return false;
                } else {
                    $ue->setModel($um);
                }
            } else {
                return false;
            }
        }
        
        return $ue;
    }
    
    // 获取当前登录的用户信息
    # => false | UserEntity
    public static function getLoginUser() {
        $ue = app()->make(UserEntity::class);
        
        if(empty($ue->id)) {
            $user_id = \Session::get('uid');
            if($user_id) {
                $um = UserModel::find($user_id);
            } else {
                $um = false;
            }
            if(!$um) {
                return false;
            } else {
                $ue->setModel($um);
            }
        }
        
        return $ue;
    }
    
    //开发用，设置当前登录用户
//     public static function setLoginUser() {
//         $ue = app()->make(UserEntity::class);
//         $user_id = '5c9c873c09235b4f58006463';
//         $um = UserModel::find($user_id);
//         $ue->setModel($um);
//         return $ue;
//     }
}